package com.kmproject.haifu.mvp.ui.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.constraint.ConstraintLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.StringUtils;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.widget.autolayout.AutoToolbar;
import com.kmproject.haifu.R;
import com.kmproject.haifu.app.service.HfLocationService;
import com.kmproject.haifu.app.utils.GoogleLocationUtil;
import com.kmproject.haifu.di.component.DaggerMapSelectAddressComponent;
import com.kmproject.haifu.mvp.contract.MapSelectAddressContract;
import com.kmproject.haifu.mvp.model.entity.beans.GooglePlaceInfoBean;
import com.kmproject.haifu.mvp.model.entity.beans.GooglePlaceInfoTextSearchBean;
import com.kmproject.haifu.mvp.model.entity.beans.HousePayWayBean;
import com.kmproject.haifu.mvp.model.entity.resbean.HFLocationBean;
import com.kmproject.haifu.mvp.model.entity.resbean.SelectAddressMapBean;
import com.kmproject.haifu.mvp.presenter.MapSelectAddressPresenter;
import com.kmproject.haifu.mvp.ui.adapter.SelectAddressMapAdapter;
import com.xw.repo.XEditText;

import org.simple.eventbus.Subscriber;
import org.simple.eventbus.ThreadMode;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import timber.log.Timber;

import static com.jess.arms.utils.Preconditions.checkNotNull;

/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 07/03/2019 00:44
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 */
public class MapSelectAddressActivity extends BaseActivity<MapSelectAddressPresenter> implements MapSelectAddressContract.View, OnMapReadyCallback, TextView.OnEditorActionListener, View.OnKeyListener {

    @BindView(R.id.toolbar_back)
    RelativeLayout toolbarBack;
    @BindView(R.id.toolbar_title)
    TextView toolbarTitle;
    @BindView(R.id.back_right_icon)
    ImageView backRightIcon;
    @BindView(R.id.back_right_txt)
    TextView backRightTxt;
    @BindView(R.id.toolbar_right)
    RelativeLayout toolbarRight;
    @BindView(R.id.toolbar)
    AutoToolbar toolbar;
    @BindView(R.id.mapview)
    MapView mapview;
    GoogleMap mgoogleMap;
    @BindView(R.id.map_select_address_Title_txt)
    TextView mapSelectAddressTitleTxt;
    @BindView(R.id.map_select_address_detial_txt)
    TextView mapSelectAddressDetialTxt;
    @BindView(R.id.map_select_address_content_img)
    ImageView mapSelectAddressContentImg;
    @BindView(R.id.linearLayout3)
    ConstraintLayout linearLayout3;
    @BindView(R.id.user_phone_txt)
    XEditText userPhoneTxt;
    @BindView(R.id.tv_search)
    TextView tv_search;
    @BindView(R.id.tv_select_region)
    TextView tvSelectRegion;
    @BindView(R.id.ll_map_select_top_layout)
    LinearLayout llMapSelectTopLayout;
    @BindView(R.id.v_map_select_top_layout_line)
    View vMapSelectTopLayoutLine;
    @BindView(R.id.v_half_white_layout)
    View vHalfWhiteLayout;

    @BindView(R.id.map_select_address_content_RecyclerView)
    RecyclerView mapSelectAddressContentRecyclerView;
    @BindView(R.id.map_select_address_keyword_search_rv)
    RecyclerView mapSelectAddressKeywordSearchRv;

    private GoogleApiClient mGoogleApiClient;
    Geocoder geocoder;
    SelectAddressMapAdapter selectAddressMapAdapter;
    SelectAddressMapAdapter selectAddressKeywordSearchAdapter;
    private String city = "";
    private String state = "";
    private String country = "";
    private String postalCode = "";
    private String knownName = "";
    private String historyName = "";
    private List<SelectAddressMapBean> selectAddressMapBeans = new ArrayList<>();
    private List<SelectAddressMapBean> selectAddressKeywordSearchBeans = new ArrayList<>();
    private String currentLat;
    private String currentLng;
    private String selectedAreaName;
    private String lat;
    private String lng;

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerMapSelectAddressComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .view(this)
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_map_select_address; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        Intent intentData = getIntent();
        if (intentData != null) {
            selectedAreaName = intentData.getStringExtra("selectedAreaName");
            lat = intentData.getStringExtra("lat");
            lng = intentData.getStringExtra("lng");
//            if (!StringUtils.isEmpty(selectedAreaName)) {
//                tvSelectRegion.setText(selectedAreaName);
//            }
        }

        ArmsUtils.configRecyclerView(mapSelectAddressContentRecyclerView, new LinearLayoutManager(this));
        selectAddressMapAdapter = new SelectAddressMapAdapter(new ArrayList<>());
        mapSelectAddressContentRecyclerView.setAdapter(selectAddressMapAdapter);
        selectAddressMapAdapter.setOnItemClickListener((adapter, view, position) -> {
            Intent intent = new Intent();
            intent.putExtra("SelectAddressMapBean", selectAddressMapAdapter.getData().get(position));
            setResult(RESULT_OK, intent);
            killMyself();
        });
        ArmsUtils.configRecyclerView(mapSelectAddressKeywordSearchRv, new LinearLayoutManager(this));
        selectAddressKeywordSearchAdapter = new SelectAddressMapAdapter(new ArrayList<>());
        mapSelectAddressKeywordSearchRv.setAdapter(selectAddressKeywordSearchAdapter);
        selectAddressKeywordSearchAdapter.setOnItemClickListener((adapter, view, position) -> {
            mapSelectAddressKeywordSearchRv.setVisibility(View.GONE);

            Intent intent = new Intent();
            intent.putExtra("SelectAddressMapBean", selectAddressKeywordSearchAdapter.getData().get(position));
            setResult(RESULT_OK, intent);
            killMyself();
        });
//         placesClient = Places.createClient(this);
        geocoder = new Geocoder(MapSelectAddressActivity.this, Locale.getDefault());
        startService(new Intent(this, HfLocationService.class));
        try {
            MapsInitializer.initialize(this);
        } catch (Exception e) {
            e.printStackTrace();
        }

        int errorCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
        if (ConnectionResult.SUCCESS != errorCode) {
            GooglePlayServicesUtil.getErrorDialog(errorCode, this, 0).show();
        } else {
            mapview.getMapAsync(this);
        }
        userPhoneTxt = findViewById(R.id.user_phone_txt);
        userPhoneTxt.setOnEditorActionListener(this);
        userPhoneTxt.setOnKeyListener(this);
        userPhoneTxt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String str = s.toString().trim();
                if (StringUtils.isTrimEmpty(str)) {
                    tv_search.setVisibility(View.GONE);
                    mapSelectAddressKeywordSearchRv.setVisibility(View.GONE);
                    selectAddressKeywordSearchBeans.clear();
                } else {
                    tv_search.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    private void search(String keyword) {
        KeyboardUtils.hideSoftInput(this);
        if (keyword.length() > 0) {
            assert mPresenter != null;
            keyword = keyword + selectedAreaName;
            mPresenter.keywordSearchRequest(keyword, currentLat, currentLng, "cn");//todo 暂为中国地区
        } else {
            mapSelectAddressKeywordSearchRv.setVisibility(View.GONE);
            selectAddressKeywordSearchBeans.clear();
        }
    }

    @OnClick({R.id.tv_select_region, R.id.tv_search})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_select_region:
                //            initDropDownMenu();
                break;
            case R.id.tv_search:
                search(userPhoneTxt.getTextEx());
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        mapview.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
//        mapview.onPause();
    }

    @SuppressLint({"MissingPermission", "CheckResult"})
    @Override
    public void onMapReady(GoogleMap googleMap) {
        Timber.i("-------------onMapReady------------");
        mgoogleMap = googleMap;
        mgoogleMap.setMyLocationEnabled(true);

        if (!StringUtils.isEmpty(lat) && !StringUtils.isEmpty(lng)) {
            try {
                CameraPosition cameraPosition = new CameraPosition.Builder()
                        .target(new LatLng(Double.parseDouble(lat), Double.parseDouble(lng)))      // Sets the center of the map to location user
                        .zoom(17)                   // Sets the zoom
                        .bearing(90)                // Sets the orientation of the camera to east
                        .tilt(40)                   // Sets the tilt of the camera to 30 degrees
                        .build();                   // Creates a CameraPosition from the builder
                mgoogleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
            } catch (Exception e) {
                location();
            }
        } else {
            location();
        }

        mgoogleMap.setOnCameraIdleListener(() -> {
            //得到地图正中心的经纬度
            LatLng center = mgoogleMap.getCameraPosition().target;
            if (center.latitude == 0 || center.longitude == 0) return;
//            double[] latlgt = GPSUtil.gps84_To_Gcj02(center.latitude, center.longitude);
//            currentLat = String.valueOf(latlgt[0]);
//            currentLng = String.valueOf(latlgt[1]);
            currentLat = String.valueOf(center.latitude);
            currentLng = String.valueOf(center.longitude);
            if (currentLat.length() > 9) {
                currentLat = currentLat.substring(0, 9);
            }
            if (currentLng.length() > 9) {
                currentLng = currentLng.substring(0, 9);
            }

            List<Address> addresses = null;
            try {
//                addresses = geocoder.getFromLocation(latlgt[0], latlgt[1], 1);
                addresses = geocoder.getFromLocation(center.latitude, center.longitude, 1);
                if (addresses != null && addresses.size() > 0) {
                    mapSelectAddressTitleTxt.setText(addresses.get(0).getFeatureName());
                    mapSelectAddressDetialTxt.setVisibility(View.VISIBLE);
                    mapSelectAddressDetialTxt.setText(addresses.get(0).getAddressLine(0));
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                assert mPresenter != null;
                mPresenter.nearbySearchRequest(currentLat, currentLng);
//                mPresenter.nearbySearchRequest("25.060606", "102.7123");
            } catch (Exception e) {
                Timber.i("no address getINSTANCE");
                e.printStackTrace();
            }
        });
    }

    private void location() {
        GoogleLocationUtil.getInstance(MapSelectAddressActivity.this).setOnLocationFinishListener(new GoogleLocationUtil.OnLocationFinishListener() {
            @Override
            public void locationFinish(SelectAddressMapBean locateCity) {
                if (locateCity != null) {
                    mapSelectAddressTitleTxt.setText(locateCity.getTitle());
                    mapSelectAddressDetialTxt.setVisibility(View.VISIBLE);
                    mapSelectAddressDetialTxt.setText(locateCity.getDetileAddress());

                    CameraPosition cameraPosition = new CameraPosition.Builder()
                            .target(new LatLng(locateCity.getLat4Double(), locateCity.getLgt4Double()))      // Sets the center of the map to location user
                            .zoom(17)                   // Sets the zoom
                            .bearing(90)                // Sets the orientation of the camera to east
                            .tilt(40)                   // Sets the tilt of the camera to 30 degrees
                            .build();                   // Creates a CameraPosition from the builder
                    mgoogleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
                }
            }

            @Override
            public void fail(String message) {
                ArmsUtils.makeText(MapSelectAddressActivity.this, message);
            }
        }).setJustOnce(true).findCurrentPlace();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mapview != null)
            mapview.onDestroy();
        GoogleLocationUtil.getInstance(this).stopLocation();
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        mapview.onCreate(savedInstanceState);
    }

    @Subscriber(mode = ThreadMode.MAIN)
    public void reciverLocation(HFLocationBean bdLocation) {
        showMessage("获取到定位信息了");
//        mgoogleMap.animateCamera(CameraUpdateFactory.newLatLng(new LatLng(bdLocation.getMlocation().getLatitude(), bdLocation.getMlocation().getLongitude())));
    }

    @Override
    public void nearbySearchRequestSuccess(GooglePlaceInfoBean result) {
        Timber.i(result.getNext_page_token());
        if (result.getStatus().equalsIgnoreCase("ok")) {
            if (result.getResults() != null && result.getResults().size() > 0) {
                SelectAddressMapBean selectAddressMapBean;
                List<GooglePlaceInfoBean.ResultsBean> resultsBeanList = result.getResults();
                selectAddressMapBeans.clear();
                for (GooglePlaceInfoBean.ResultsBean resultsBean : resultsBeanList) {
                    if (resultsBean.getTypes().contains("locality") || resultsBean.getTypes().contains("political")) {
                        continue;
                    }
                    selectAddressMapBean = new SelectAddressMapBean();
                    selectAddressMapBean.setTitle(resultsBean.getName());
                    selectAddressMapBean.setDetileAddress(resultsBean.getVicinity());
                    selectAddressMapBean.setLat(String.valueOf(resultsBean.getGeometry().getLocation().getLat()));
                    selectAddressMapBean.setLgt(String.valueOf(resultsBean.getGeometry().getLocation().getLng()));
                    selectAddressMapBeans.add(selectAddressMapBean);
                }
                selectAddressMapAdapter.setNewData(selectAddressMapBeans);
                for (SelectAddressMapBean s : selectAddressMapBeans) {
                    String sb = s.getTitle() +
                            "\n" +
                            s.getDetileAddress() +
                            "\n" +
                            s.getLat() +
                            "\n" +
                            s.getLgt();
                    Timber.d(sb);
                }
            }
        }
    }

    @Override
    public void keywordSearchRequestSuccess(GooglePlaceInfoTextSearchBean result) {
        Timber.i(result.getStatus());
        if (result.getStatus().equalsIgnoreCase("ok")) {
            if (result.getResults() != null && result.getResults().size() > 0) {
                SelectAddressMapBean selectAddressMapBean;
                List<GooglePlaceInfoTextSearchBean.ResultsBean> resultsBeanList = result.getResults();
                selectAddressKeywordSearchBeans.clear();
                mapSelectAddressKeywordSearchRv.setVisibility(View.VISIBLE);
                for (GooglePlaceInfoTextSearchBean.ResultsBean resultsBean : resultsBeanList) {
                    if (resultsBean.getTypes().contains("locality") || resultsBean.getTypes().contains("political")) {
                        continue;
                    }
                    selectAddressMapBean = new SelectAddressMapBean();
                    selectAddressMapBean.setTitle(resultsBean.getName());
                    selectAddressMapBean.setDetileAddress(resultsBean.getFormatted_address());
                    selectAddressMapBean.setLat(String.valueOf(resultsBean.getGeometry().getLocation().getLat()));
                    selectAddressMapBean.setLgt(String.valueOf(resultsBean.getGeometry().getLocation().getLng()));
                    selectAddressKeywordSearchBeans.add(selectAddressMapBean);
                }
                selectAddressKeywordSearchAdapter.setNewData(selectAddressKeywordSearchBeans);
                for (SelectAddressMapBean s : selectAddressKeywordSearchBeans) {
                    String sb = s.getTitle() +
                            "\n" +
                            s.getDetileAddress() +
                            "\n" +
                            s.getLat() +
                            "\n" +
                            s.getLgt();
                    Timber.d(sb);
                }
            }
        }
    }

    @Override
    public void showRegionPopUpWindow(List<HousePayWayBean> houseArea) {
    }

    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_ENTER) {
            // 搜索
            if (!StringUtils.isTrimEmpty(userPhoneTxt.getTextEx())) {
                search(userPhoneTxt.getTextEx());
            }
            return true;
        }
        return false;
    }

    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        switch (actionId) {
            case EditorInfo.IME_ACTION_SEARCH:
            case EditorInfo.IME_ACTION_DONE:
            case EditorInfo.IME_ACTION_GO:
            case EditorInfo.IME_ACTION_NEXT:
            case EditorInfo.IME_ACTION_SEND: {
                // 搜索
                if (!StringUtils.isTrimEmpty(userPhoneTxt.getTextEx())) {
                    KeyboardUtils.hideSoftInput(this);
                    search(userPhoneTxt.getTextEx());
                }
                return true;
            }
        }
        return false;
    }
}
